<template>
    <page-box class="custom-page-box">
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <div class="userList-table-container">
            <div class="number-info">
                <div class="blue">
                    <p>截止<span class="time">{{ nowTime }}</span>用户数共</p>
                    <p>
                        <span>{{ userNum }}</span>名
                    </p>
                </div>
                <div class="red">
                    <p>截止<span class="time">{{ nowTime }}</span>冻结用户数共</p>
                    <p>
                        <span>{{ userNumFrozen }}</span>名
                    </p>
                </div>
            </div>
            <page-search>
                <page-search-column class="fixed-column">
                    <page-search-item>
                        <el-input class="pbb__search-input" v-model="form.keyword" placeholder="姓名/账户"></el-input>
                    </page-search-item>
                    <page-search-item>
                        <el-cascader
                            class="pbb__search-input"
                            v-model="form.cityCode"
                            :options="options"
                            :props="props"
                            placeholder="所在区镇村"
                            clearable
                            @visible-change="visibleChange"
                            @change="cascaderChange"
                            :key="key">
                        </el-cascader>
                    </page-search-item>
                    <page-search-item>
                        <el-select class="pbb__search-input user" v-model="form.type" placeholder="用户类型" clearable multiple collapse-tags>
                            <el-option :value="1" label="系统内成员"></el-option>
                            <el-option :value="3" label="村民"></el-option>
                            <el-option :value="4" label="企业"></el-option>
                        </el-select>
                    </page-search-item>
                    <page-search-item>
                        <el-select class="pbb__search-input" v-model="form.status" placeholder="激活状态" clearable>
                            <el-option :value="1" label="正常"></el-option>
                            <el-option :value="2" label="冻结"></el-option>
                        </el-select>
                    </page-search-item>
                    <page-search-item>
                        <el-date-picker
                            class="pbb__search-input date"
                            v-model="form.createTime"
                            type="daterange"
                            range-separator="~"
                            start-placeholder="开始创建日期"
                            end-placeholder="结束创建日期"
                            value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </page-search-item>
                    <page-search-item>
                        <el-button type="primary" @click="getTable">搜索</el-button>
                    </page-search-item>
                </page-search-column>
            </page-search>
            <el-table
                ref="multipleTable"
                :data="tableData"
                class="pbb__table"
                header-cell-class-name="pbb__table-thead"
                cell-class-name="pbb__table-thead-cell"
                row-class-name="pbb__table-thead-row"
                style="width: 100%;height: calc(100% - 58px);overflow-y: auto;">
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    width="60">
                </el-table-column>
                <el-table-column
                    label="姓名"
                    prop="name">
                </el-table-column>
                <el-table-column
                    label="区镇村"
                    prop="governmentName">
                </el-table-column>
                <el-table-column
                    label="账户"
                    prop="username">
                </el-table-column>
                <el-table-column
                    label="部门"
                    prop="departmentName">
                </el-table-column>
                <el-table-column
                    label="职位"
                    prop="position">
                </el-table-column>
                <el-table-column
                    label="激活状态"
                    prop="status">
                    <template slot-scope="scope">
                        <span>{{ scope.row.status === 1 ? "正常" : "冻结" }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="最近登录时间"
                    prop="lastTime">
                </el-table-column>
                <el-table-column
                    label="创建时间"
                    prop="createTime">
                </el-table-column>
                <el-table-column
                    label="操作"
                    show-overflow-tooltip
                    min-width="120">
                    <template slot-scope="scope">
                        <el-button type="text" @click="resetPw(scope.row)">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <template v-slot:footer v-if="total > 0">
            <pagination v-show="total > 0" :total="total" :page.sync="pageIndex" :limit.sync="pageSize" @pagination="getTable"/>
        </template>
        <el-dialog
            title="重置密码"
            :visible.sync="dialogVisible"
            width="30%">
            <el-form :model="resetForm" ref="dialogForm" :rules="rules" :inline="true">
                <el-form-item label="新密码" prop="newPassword" required class="newPassword">
                    <el-input id="newPassword" v-model="resetForm.newPassword" placeholder="请设置6~12位数字字母组合新密码" show-password></el-input>
                    <i class="el-icon-refresh-right svg-icon" @click="randomCode"></i>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="mini">取消</el-button>
                <el-button type="primary" @click="save" size="mini">确定并复制</el-button>
            </span>
        </el-dialog>
    </page-box>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";


const checkPassword = (rule: any, value: any, callback: any) => {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
    if (!reg.test(value) || !value) {
        callback(new Error('请设置6~12位数字字母组合新密码'));
    } else {
        callback();
    }
};

@Component({
    name: "UserListNotAlive"
})
export default class UserList extends Vue {
    form: any = {
        keyword: "",
        cityCode: [],
        type: [],
        status: "",
        createTime: []
    }

    // 表格数据
    tableData: any = []
    // 总数
    total = 0
    // 页码
    pageIndex = 1
    // 每页数量
    pageSize = 10

    options: any[] = []

    dialogVisible = false

    resetForm: any = {
        newPassword: ""
    }

    currentId = ""
    userNum = ""
    userNumFrozen = ""
    nowTime = ""

    rules = {
        newPassword: [
            { validator: checkPassword, trigger: ["blur", "change"] }
        ]
    }

    props = {
        checkStrictly: true,
        value: 'code',
        label: 'name',
        lazy: true,
        lazyLoad: async(node: any, resolve: any) => {
            const res: any = await this.getOptions(node.value);
            resolve(res);
        }
    }

    key = 0

    created() {
        this.getTable();
        this.nowTime = new Date().format("yyyy-MM-dd hh:mm");
    }

    async getOptions(code?: any) {
        let list: any[] = [];
        const res = await this.$server["userList/getArea"]({
            data: {
                code: code || ""
            },
            loader: false
        });
        if (res.data.code === 200) {
            list = res.data.data;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
        return list;
    }

    getTable() {
        const { keyword, cityCode, type, status, createTime } = this.form;
        this.$server["userList/table"]({
            data: {
                pageSize: this.pageSize,
                currentPage: this.pageIndex,
                name: keyword || null,
                cityCode: cityCode[cityCode.length - 1] || null,
                userType: type,
                status: status || null,
                startCreated: createTime ? (createTime[0] ? createTime[0] + ' 00:00:00' : null) : null,
                endCreated: createTime ? (createTime[1] ? createTime[1] + ' 23:59:59' : null) : null
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.tableData = res.data.data.userVoPage.records || [];
                this.total = res.data.data.userVoPage.total;
                this.userNum = res.data.data.userNum;
                this.userNumFrozen = res.data.data.userNumFrozen;
                this.nowTime = new Date().format("yyyy-MM-dd hh:mm");
            } else {
                this.$message.error(res.data.message || "接口请求错误!");
            }
        }).catch();
    }

    visibleChange(show: any) {
        if (!show && !this.form.cityCode.length) {
            this.key++;
        }
    }

    cascaderChange() {
        if (!this.form.cityCode.length) {
            this.key++;
        }
    }

    resetPw(row: any) {
        this.currentId = row.id;
        this.dialogVisible = true;
    }

    closeDialog() {
        (this.$refs.dialogForm as any).resetFields();
        this.dialogVisible = false;
    }

    randomCode() {
        const RandomRange = (min: any, max: any): string => {
            let returnStr = "";
            const range = (max ? Math.round(Math.random() * (max - min)) + min : min);
            const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            for (let i = 0; i < range; i++) {
                const index = Math.round(Math.random() * (arr.length - 1));
                returnStr += arr[index];
            }
            if (returnStr.match(/\d/g)) {
                return returnStr;
            } else {
                return RandomRange(6, 12);
            }
        };
        this.resetForm.newPassword = RandomRange(6, 12);
    }

    save() {
        (this.$refs.dialogForm as any).validate((valid: any) => {
            if (valid) {
                this.$server["userList/resetPw"]({
                    data: {
                        id: this.currentId,
                        password: this.resetForm.newPassword
                    }
                }).then((res: any) => {
                    if (res.data.code === 200) {
                        this.copy(this.resetForm.newPassword);
                        this.$message.success("重置成功");
                        this.closeDialog();
                    } else {
                        this.$message.error(res.data.message || "接口请求错误!");
                    }
                }).catch();
            }
        });
    }

    copy(data: any) {
        const input = document.createElement('input');
        input.value = data;
        document.body.appendChild(input);
        input.select();
        document.execCommand('Copy');
        document.body.removeChild(input);
    }
}
</script>
<style lang="scss" scoped>
::v-deep {
    .pbb__search-box {
        margin-bottom: 10px;
    }
}
.pbb__search-input {
    width: 150px;
    &.user {
        width: 200px;
    }
    &.date {
        width: 260px;
    }
}
.number-info {
    width: 100%;
    height: 60px;
    @include flexLayout(flex,normal,normal);
    margin-bottom: 10px;
    color: #37383a;
    div {
        width: 40%;
        margin-right: 20px;
        padding: 10px 20px;
        @include flexLayout(flex,justify,center);
        p {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 500;
            margin: 0;
            display: inline-block;
            span {
                font-size: 28px;
                font-weight: bold;
            }
            .time {
                font-size: 14px;
                color: #497FDE;
                font-weight: normal;
                margin: 0 4px;
            }
        }
        &.red {
            background: #EED5D2;
            border-left: 4px solid #DF412E;
        }
        &.blue {
            background: #DAE7F1;
            border-left: 4px solid #497FDE;
        }
    }
}
.newPassword {
    ::v-deep {
        .el-form-item__content {
            display: inline-flex;
            align-items: center;
        }
    }
    .svg-icon {
        margin-left: 10px;
        font-size: 18px;
        padding: 4px;
        cursor: pointer;
        color: #2C82C9;
    }
}
</style>
